package com.UdpRecieve.secret.utils;

import com.UdpRecieve.domain.FilePigeonhole;
import com.UdpRecieve.secret.model.SBR_Parameter_Table;
import com.UdpRecieve.secret.model.SecretLableCheckModel;
import com.UdpRecieve.secret.domain.SecretLableResult;
import com.UdpRecieve.tool.http.HttpClientFactory;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * 盛博睿-秘标接口-本地版(single)
 */
public class SECRECT_SBR {
    private static CloseableHttpClient httpClient = HttpClientFactory.INSTANCE();

    private static String ip = "127.0.0.1";
    /**
     * 文件加标
     * @param filePath 该文件名是文件上传后的filename属性不是源文件名
     * @return
     */
    public static String StandardAddition(String filePath){
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
        CloseableHttpResponse response = null;
        String responseString = null;
        String url = "https://" + ip + ":1257/api/v1/client/addLabel/";
        HttpPost httpPost = new HttpPost(url);
        String label = "{\"labelSpecId\":1,\"labelSpecVersion\":1,\"algoSpecId\":1,\"algoSpecVersion\":1,\"level\":150,\"fileContentId\":\"\",\"fileUniqueId\":\"\",\"fileAssetId\":\"\",\"duration\":{\"classifiedTime\":\"\",\"period\":\"999999\",\"condition\":\"1\",\"declassifiedTime\":\"\"},\"status\":110,\"drafter\":{\"id\":\"0e887468-f53a-46f8-aa6d-2562b4b79da0\",\"name\":\"test\"},\"authority\":{\"id\":\"\",\"name\":\"\"},\"issuer\":{\"id\":\"\",\"name\":\"\"},\"organs\":[{\"id\":\"37bf5a52-d5af-4fdd-a901-a487d8925471\",\"name\":\" 国务院\"}],\"scope\":{\"description\":\"1\",\"staffs\":[],\"groups\":[],\"units\":[]},\"basises\":{\"type\":10,\"description\":\"1\",\"normalItems\":[{\"id\":\"a494090c-3d3e-4b97-9304-62e05b40baca\",\"name\":\" 绩 效 管 理 有 关 信 息\",\"level\":50,\"duration\":{\"classifiedTime\":\"\",\"period\":\"999999\",\"condition\":\"\",\"declassifiedTime\":\"\"},\"scope \":\"\",\"scopeList \":[],\"keys \":[],\"handle \":\"\"},{\"id \":\"ac803f05-6d3f-4167-8884-c6b1310dc5b1 \",\"name \":\"公司人工成本信息及相关统计数据 \",\"level \":21,\"duration \":{\"classifiedTime \":\"\",\"period \":\"999999 \",\"condition \":\"\",\"declassifiedTime \":\"\"},\"scope\":\"\",\"scopeList\":[],\"keys\":[],\"handle\":\"\"}],\"derivedItems\":[]},\"histories\":[],\"keys\":[]}";
        multipartEntityBuilder.addTextBody("label",label);
        try {
            multipartEntityBuilder.addTextBody("filename",filePath, ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
        }

        HttpEntity reqEntity = multipartEntityBuilder.build();
        httpPost.setEntity(reqEntity);
        try {
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if(responseEntity!=null){
                responseString = EntityUtils.toString(responseEntity);
                System.out.println("响应内容为:" + responseString);
            }
        } catch (IOException e) {
            System.out.println("http请求异常，地址"+url);
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (response != null)
                    response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseString;
    }



    /**
     * 文件验标
     * @param filePath 文件上传后返回的 fileName
     * @param filePigeonhole 文件描述对象
     * @return Boolean
     */
    public static SecretLableResult CheckStancdard(String filePath, FilePigeonhole filePigeonhole,SecretLableResult secretLableResult) {
        CloseableHttpResponse response = null;
        String responseString = null;
        String url = "https://127.0.0.1:1257/api/v1/client/getFileLabel/";
        URIBuilder uriBuilder = null;
        try {
            uriBuilder = new URIBuilder(url);
            List<NameValuePair> list = new LinkedList<>();
            BasicNameValuePair param = new BasicNameValuePair("filename", filePath);
            list.add(param);
            uriBuilder.setParameters(list);
            // 根据带参数的URI对象构建GET请求对象
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            RequestConfig defaultConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
            httpGet.setConfig(defaultConfig);
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if(responseEntity!=null){
                responseString = EntityUtils.toString(responseEntity);
                //System.out.println("验标接口响应内容为:" + responseString);
                JSONObject jsonObject = JSONObject.parseObject(responseString);
                String label = jsonObject.getString("label");
                jsonObject = JSONObject.parseObject(label);


                //定密责任人(审批人)
                secretLableResult.setAuthority(
                        JSONObject.parseObject(jsonObject.getString("authority")).getString("name")
                );
                //起草人
                secretLableResult.setDrafter(
                        JSONObject.parseObject(jsonObject.getString("drafter")).getString("name")
                );
                //扩展属性
                secretLableResult.setExtend("工控业务");
                //文件密级
                secretLableResult.setLevel(jsonObject.getString("level"));
                //管理状态
                secretLableResult.setStatus(jsonObject.getString("status"));
                //检验并返回检验结果
                secretLableResult =  checkResult(secretLableResult,filePigeonhole);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (response != null)response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return secretLableResult;
    }

    /**
     * 检验结果的封装
     * @param secretLableResult
     * @param filePigeonhole
     * @return
     */
    private static SecretLableResult checkResult(SecretLableResult secretLableResult, FilePigeonhole filePigeonhole){
        int a,b,c,d,e;
        //审批人验证结果
        secretLableResult.setSecret_authority_isOk(a=1);
        //起草人验证结果
        secretLableResult.setSecret_drafter_isOk(b=1);
        //文件密级验证结果
        String level = SBR_Parameter_Table.getLevel(secretLableResult.getLevel());
        secretLableResult.setSecret_level_isOk(
                c= level.equals(SecretLableCheckModel.LEVEL.VALUE())
                        ||level.equals(SecretLableCheckModel.LEVEL2.VALUE()) ?1:0
        );
        //管理状态验证结果
        secretLableResult.setSecret_status_isOk(
                d=SBR_Parameter_Table.getStatus(secretLableResult.getStatus()).equals(SecretLableCheckModel.STATUS.VALUE())?1:0
        );
        //扩展属性验证结果
        secretLableResult.setSecret_extend_isOk(e=1);
        //最终检验结果
        secretLableResult.setSecret_result(
                a==1&&b==1&&c==1&&d==1&&e==1
        );
        return secretLableResult;
    }

    /**
     * 文件解标
     * @param filePath 文件名称
     * @return Boolean
     */
    public static Boolean StandardSubtraction(String filePath){
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
        multipartEntityBuilder.setCharset(Consts.UTF_8);
        Boolean result = false;
        CloseableHttpResponse response = null;
        String responseString = null;
        String url = "https://127.0.0.1:1257/api/v1/client/removeLabel/";
        HttpPost httpPost = new HttpPost(url);

        multipartEntityBuilder.addTextBody("filename",filePath, ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8));

        HttpEntity reqEntity = multipartEntityBuilder.build();
        httpPost.setEntity(reqEntity);
        RequestConfig defaultConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
        httpPost.setConfig(defaultConfig);
        try {
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if(responseEntity!=null){
                responseString = EntityUtils.toString(responseEntity);
                //System.out.println("解标接口响应内容为:" + responseString);
                if("null".equals(responseString)){
                    result = true;
                }
            }
        } catch (IOException e) {
            System.out.println("http请求异常，地址"+url);
            e.printStackTrace();
        } finally {
            try {
                if (response != null)
                    response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }




    /**
     * 文件验标
     * @param filePath 文件上传后返回的 fileName
     * @return Boolean
     */
    public static void CheckStancdard2(String filePath) {
        CloseableHttpResponse response = null;
        String responseString = null;
        String url = "https://127.0.0.1/api/v1/client/getFileLabel/";
        URIBuilder uriBuilder = null;
        try {
            uriBuilder = new URIBuilder(url);
            List<NameValuePair> list = new LinkedList<>();
            BasicNameValuePair param = new BasicNameValuePair("filename", filePath);
            list.add(param);
            uriBuilder.setParameters(list);
            // 根据带参数的URI对象构建GET请求对象
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if(responseEntity!=null){
                responseString = EntityUtils.toString(responseEntity);
                //System.out.println("验标接口响应内容为:" + responseString);
                JSONObject jsonObject = JSONObject.parseObject(responseString);
                String label = jsonObject.getString("label");
                jsonObject = JSONObject.parseObject(label);
                System.out.println(label);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (response != null)response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        /*StandardSubtraction("F:\\Home02\\Send02\\xml格式.txt");*/

        CheckStancdard2("F:\\Home02\\Send02\\xml格式.txt");
    }
}
